﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Collections;
using System.Data.SqlClient;



using System.IO;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Data.Entity;
using System.Text.RegularExpressions;
using System.Net.NetworkInformation;
using System.Net;
using System.Dynamic;
using ABDLight.Components;
using System.Diagnostics;
using System.Collections;
using System.Threading;



namespace ABDLight
{
    public partial class frmMine : Form
    {
       // public static readonly ILog log = LogManager.GetLogger(typeof(frmMine));

        public DataTable dtMain = new DataTable();
        public DataTable dtVariant = new DataTable();

        SqlConnection con;
        SqlDataAdapter adap;

        DataTable dt;
        SqlCommandBuilder cmdbl;

        int SelectedRowIndex;
        int SelectedColumnIndex;
       

        public Config cfg = new Config();


        public frmMine()
        {
            //Просто информация
            //log.Info("== Инициализация формы Mine ==");

            InitializeComponent();

            //==== Заполнение экземпляра класса Config - cfg:
            cfg.Login = ABDLight.Properties.Settings.Default.Login;
            cfg.edPass = ABDLight.Properties.Settings.Default.edPwd;
            cfg.TmpDir = ABDLight.Properties.Settings.Default.TmpDir;
            cfg.defCountry = ABDLight.Properties.Settings.Default.defCountry;
            ABDLight.Properties.Settings.Default.DefFilePath = Application.StartupPath;
            cfg.DefFilePath = ABDLight.Properties.Settings.Default.DefFilePath;
            //====
            cfg.CheckEmail = ABDLight.Properties.Settings.Default.CheckEmail;
            cfg.CheckFIO = ABDLight.Properties.Settings.Default.CheckFIO ;
            cfg.CheckPhone = ABDLight.Properties.Settings.Default.CheckPhone;
            cfg.SelectAddr_Url = ABDLight.Properties.Settings.Default.SelectAddr_Url;
            cfg.SearchAddr_Url = ABDLight.Properties.Settings.Default.SearchAddr_Url;
            cfg.DB = ABDLight.Properties.Settings.Default.DB;
            cfg.Table = ABDLight.Properties.Settings.Default.Table;
            cfg.CheckOrgDubl_Url = ABDLight.Properties.Settings.Default.CheckOrgDubl;
            cfg.AddressCleanASMX_Url = ABDLight.Properties.Settings.Default.AddressCleanASMX;
            cfg.isJSON = ABDLight.Properties.Settings.Default.isJSON;

            cfg.isUseDB = ABDLight.Properties.Settings.Default.isUseDB;
            cfg.MaxRowsToRead = ABDLight.Properties.Settings.Default.MaxRowsToRead;

            String str = "";
            if (!File.Exists(ABDLight.Properties.Settings.Default.DB + ".db"))
            {
                str = "Data Source=" + ABDLight.Properties.Settings.Default.DB + ".db" + ";Version=3;New=True;Compress=True;Password=" + ABDLight.Properties.Settings.Default.Password + ";";
            }
            else if (File.Exists(ABDLight.Properties.Settings.Default.DB + ".db"))
            {
                str = "Data Source=" + ABDLight.Properties.Settings.Default.DB + ".db" + ";Version=3;New=False;Compress=True;Password=" + ABDLight.Properties.Settings.Default.Password  + ";";
            }


            //====
            //Тестовое заполнение/начитка INI файла
            string isStart = "";
            aejw.cIni oIni = new aejw.cIni(Application.StartupPath + "\\settings.ini");
            isStart = oIni.ReadValue("start", "isStart", "0");
            oIni.WriteValue("start", "isStart", "1");
            isStart = oIni.ReadValue("start", "isStart", "0");
            isStart = oIni.ReadValue("AppConfig", "AppPath", Application.StartupPath);         
            //====    
        
            this.ClientSize = new System.Drawing.Size(SystemInformation.PrimaryMonitorSize.Width / 2, SystemInformation.PrimaryMonitorSize.Height / 4 );
        }
        /*//////////////////////////////////////////////////////////////////////////////////////
            //Пример обхода всех TextBoxов
            //foreach (Control control in Controls)
            //{
            //    TextBox tb = control as TextBox;
            //    if (tb != null)
            //    {
            //        tb.Text = "Text";
            //    }
            //}
        *////////////////////////////////////////////////////////////////////////////////////////
        

        public void SettingsINI(string func, string file)
        {
            
        }

        public void mnuExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void mnuLoad_Click(object sender, EventArgs e)
        {
            frmLoad frm = new frmLoad();
            frm.Owner = this;
            frm.Show();           
        }

        private void mnuResult_Click(object sender, EventArgs e)
        {
            OpenFrmClean();
        }
        public void OpenFrmClean()
        {
            foreach (Form f in this.OwnedForms)
            {
                if (f.Name == "frmLoad")
                {
                    f.Close();
            
                }
            }
            foreach (Form f in this.OwnedForms)
            {
                if (f.Name == "frmClean")
                {
                    f.Activate();
                    return;
                }
            }
            frmClean frm = new frmClean();
            frm.Owner = this;
            frm.Show();
            frm.LoadForm();
        }

        private void mnuSettings_Click(object sender, EventArgs e)
        {
            frmSettings frm = new frmSettings();
            frm.Owner = this;
            //frm.ShowDialog();
            while (frm.ShowDialog() == DialogResult.Retry) { }
        }


        private void frmMine_Load(object sender, EventArgs e)
        {
            notifyIcon_TrayIcon.ShowBalloonTip(15000);
            frmLogin frm = new frmLogin();
            frm.Owner = this;

            if (frm.ShowDialog() == DialogResult.Cancel) this.Close();
            //while (frm.ShowDialog() == DialogResult.Retry) { }


            this.IsMdiContainer = true;

            Hashtable pars = new Hashtable();
            pars.Add("Execute", "CheckCleanFile");

            frmProgress.frm = new frmProgress();
            frmProgress.frm.Owner = Program.applicationContext.MainForm;
            frmProgress.frm.ExecuteCommand("CheckFile", pars);
            //frmProgress frmP = new frmProgress();
            //frmP.Owner = Program.applicationContext.MainForm;
            //frm.ExecuteCommand("CheckFile", frmP, pars);
        }

        public void OpenTextFile(string file, DataTable dt, string cPage, string separator = ";", bool HDR = true, bool KOV = false, bool isPreview = false)
        {
            
            if (File.Exists(file))
            {
                if (separator == "tab") separator = "\t";

                Encoding enc = Encoding.GetEncoding(cPage);
                using (StreamReader sr = new StreamReader(file, enc))
                {
                    dt.Rows.Clear();
                    dt.Columns.Clear();
                    if (HDR)
                        frmLoad.RecordCountInFile = System.IO.File.ReadAllLines(file).Length - 1;
                    else
                        frmLoad.RecordCountInFile = System.IO.File.ReadAllLines(file).Length;
                    string line = "";
                    int r = 0;
                    int col = 0;
                    int PreviewNum = 0;
                    string charKOV = "\\\"" ;
                    line = sr.ReadLine();
                    if (KOV)
                    {
                      //  line = Regex.Replace(line, charKOV, "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        
                    }
                    while (line != null)
                    {
                        
                        line.Trim();
                        //определение кол-ва разделителей
                        MatchCollection match1 = Regex.Matches(line, separator);
                        //Console.WriteLine("{0}", match1.Count);
                        if (KOV)
                        {
                            //определение кол-ва разделителей с учетом ковычек
                            MatchCollection match2 = Regex.Matches(line, '"' + separator + '"');
                            line = Regex.Replace(line, charKOV.ToString(), "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);                         
                        }
                        string[] row = line.Split(separator.ToCharArray()[0]);

                        if (col == 0) col = row.Length;
                        else if (row.Length != col)
                        {
                            line = sr.ReadLine();
                            continue;
                        }

                        if (r == 0)
                        {
                            for (int i = 0; i < col; i++)
                            {
                                //KOV = false;
                                if (KOV)
                                {
                                    if (HDR)
                                    {
                                        dt.Columns.Add(row[i].ToString() + "_" + i.ToString(), System.Type.GetType("System.String"));                                  
                                    }
                                    else
                                    {
                                        dt.Columns.Add("field_" + i.ToString(), System.Type.GetType("System.String"));
                                    }
                                }
                                else
                                {
                                    if (HDR)
                                    {
                                        dt.Columns.Add(row[i].ToString(), System.Type.GetType("System.String"));
                                    }
                                    else
                                    {
                                        dt.Columns.Add("field_" + i.ToString(), System.Type.GetType("System.String"));
                                    }
                                }
                            }
                           
                            if (HDR) 
                            {
                                line = sr.ReadLine();
                                r++;
                                continue;
                            } 
                             
                        }

                        DataRow dr = dt.NewRow();

                        for (int i = 0; i < col; i++)
                        {
                            /*
                            if (dt.Columns[i].ColumnName == ("ID_IQ") || dt.Columns[i].ColumnName == ("iqParentID"))
                            {
                                Int32 val = 0;
                                Int32.TryParse(row[i].ToString(), out val);
                                dr[i] = val;
                            }
                            else dr[i] = row[i].ToString();
                            */
                            dr[i] = row[i].ToString();
                        }
                        dt.Rows.Add(dr);
                        r++;

                        if (r > 100 && isPreview)
                        {                           
                            sr.Close();
                            return;
                        }
                        line = sr.ReadLine();
                     
                    }
                    sr.Close();
                }
            }
            else {

                MessageBox.Show("Не выбрано ни одного файла!", "Внимание",
                                                 MessageBoxButtons.OK,
                                                 MessageBoxIcon.Error);
            }

        }//end proc

  

        public void SaveFile(string filename,ref DataTable  dt, string  cPage, string separator = ";", bool HDR = true)
        {

            if (File.Exists(filename)) File.Delete(filename);
            
            Encoding enc = Encoding.GetEncoding(cPage);
            using (StreamWriter sw = new StreamWriter(filename, false, enc))
            {
                string line = "";
                if (HDR)
                {
                    foreach (DataColumn col in dt.Columns)
                    {
                        line += col.ColumnName + separator;
                    }
                    sw.WriteLine(line);               
                }
                line = "";
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int col = 0; col <dt.Columns.Count; col++)
                    {
                        line += dt.Rows[i][col].ToString()+separator;
                    }
                    sw.WriteLine(line);
                    line = "";
                }
                      
            MessageBox.Show("В файл "+filename+" успешно сохранено "+ dt.Rows.Count.ToString()+" записей", "Внимание",
                                             MessageBoxButtons.OK,
                                             MessageBoxIcon.Information);
             }
        }

        private void mnuExport_Click(object sender, EventArgs e)
        {
            frmExport frm = new frmExport();
            frm.Owner = this;
            frm.Show();
        }

        private void frmMine_FormClosed(object sender, FormClosedEventArgs e)
        {

            aejw.cIni oIni = new aejw.cIni(Application.StartupPath + "\\settings.ini");
            oIni.WriteValue("LastSettings", "LastFileName", ABDLight.Properties.Settings.Default.CleanFileName);
            oIni.WriteValue("LastSettings", "LastFilePath", frmClean.cCfg.LastFilePath);
            oIni.WriteValue("LastSettings", "LastFileIndex", frmClean.cCfg.LastFileIndex.ToString());
            oIni.WriteValue("LastSettings", "Login", ABDLight.Properties.Settings.Default.Login);
            oIni.WriteValue("LastSettings", "md5", ABDLight.Properties.Settings.Default.Pwd);
            string TimeCode = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString();
            oIni.WriteValue("LastSettings", "LastCleanTimeCode", TimeCode);
        }

        private void mnuAbout_Click(object sender, EventArgs e)
        {
            AboutABDLight frm = new AboutABDLight();
            frm.Owner = this;
            frm.ShowDialog();
        }

        private void toolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void pictureBox_miniLogo_Click(object sender, EventArgs e)
        {

        }

        private void openToolStripButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;
            }
        
        }

        private void newToolStripButton_Click(object sender, EventArgs e)
        {
           
            frmLoad frm = new frmLoad();
            frm.MdiParent = this;
            frm.Parent = this;
           
            frm.Show();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            string conn;
            string AddressOtvet;


            conn = "http://iqdq.ru/Services/IQDQ/SearchAddressDetail?addr=,Москва, , улица Никулинская, д.13 &login=admin&pwd=RgH75bmLTg";


            //Запуск подсчета времени выполнения
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();

            //////////////////////////////////////////
            AddressOtvet = new StreamReader(HttpWebRequest.Create(conn).GetResponse().GetResponseStream()).ReadToEnd();
            //////////////////////////////////////////

            // Останавливаем таймер 
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
            return;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            string conn;
            string AddressOtvet;


            conn = "http://iqdq.ru/Services/IQDQ/SearchAddressDetail?addr=,Moskva, , Ulica Nikulinskaja, d.13&login=admin&pwd=RgH75bmLTg";
            

            //Запуск подсчета времени выполнения
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();

            //////////////////////////////////////////
            AddressOtvet = new StreamReader(HttpWebRequest.Create(conn).GetResponse().GetResponseStream()).ReadToEnd();
            //////////////////////////////////////////

            // Останавливаем таймер 
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
            return;
        }


        private void mnuBD_Click(object sender, EventArgs e)
        {

            frmSQLiteFiles frm = new frmSQLiteFiles();
            frm.Owner = this;
            frm.Show();
        }
    }//end class


    [DataContract]
    public class Config
    {
        [DataMember]
        public string Http { get; set; }

        [DataMember]
        public string Login { get; set; }

        [DataMember]
        public string TmpDir { get; set; }
        [DataMember]
        public string Pwd { get; set; }
        [DataMember]
        public string fileName { get; set; }
        [DataMember]
        public int defCountry { get; set; }
        [DataMember]
        public string edPass { get; set; }
        [DataMember]
        public string CleanFileName { get; set; }
        [DataMember]
        public string DefFilePath { get; set; }
        [DataMember]
        public string CheckEmail { get; set; }
        [DataMember]
        public string CheckFIO { get; set; }
        [DataMember]
        public string CheckPhone { get; set; }
        [DataMember]
        public string SelectAddr_Url { get; set; }
        [DataMember]
        public string SearchAddr_Url { get; set; }
        [DataMember]
        public string DB { get; set; }
        [DataMember]
        public string Table { get; set; }
        [DataMember]
        public string CheckOrgDubl_Url { get; set; }
        [DataMember]
        public string AddressCleanASMX_Url { get; set; }
         [DataMember]
        public string isJSON { get; set; }
         [DataMember]
        public string isUseDB { get; set; }
         [DataMember]
         public string MaxRowsToRead { get; set; }
         public string Filter { get; set; }




        public Config()
        {
            Http = "";
            Login = "";
            TmpDir = "";
            fileName = "";
            Pwd = "";
            edPass = "";
            CleanFileName = "";
            DefFilePath = "";
            CheckEmail = "";
            CheckFIO = "";
            CheckPhone = "";
            SelectAddr_Url = "";
            SearchAddr_Url = "";
            DB = "";
            Table = "";
            CheckOrgDubl_Url = "";
            AddressCleanASMX_Url = "";
            isJSON = "";
            isUseDB = "";
            MaxRowsToRead = "";
            Filter = "";
        }

        public Config(string _Http, string _Login, string _TmpDir, string _fileName, int _defCountry, string _Pwd, string _edPass, string _CleanFileName, string _DefFilePath, string _CheckEmail, string _CheckFIO, string _CheckPhone = "", string _SelectAddr_Url = "", string _SearchAddr_Url = "", string _DB = "", string _Table = "", string _CheckOrgDubl_Url = "", string _AddressCleanASMX_Url = "", string _isJSON = "", string _isUseDB = "", string _MaxRowsToRead = "", string _Filter = "")
        {
            Http = _Http;
            Login = _Login;
            TmpDir = _TmpDir;
            fileName = fileName;
            Pwd = _Pwd;
            edPass = _edPass;
            CleanFileName = _CleanFileName;
            DefFilePath = _DefFilePath;
            CheckEmail = _CheckEmail;
            CheckFIO = _CheckFIO;
            CheckPhone = CheckPhone;
            SelectAddr_Url = SelectAddr_Url;
            SearchAddr_Url = SearchAddr_Url;
            DB = _DB;
            Table = _Table;
            CheckOrgDubl_Url = _CheckOrgDubl_Url;
            AddressCleanASMX_Url = _AddressCleanASMX_Url;
            isJSON = _isJSON;
            isUseDB = _isUseDB;
            MaxRowsToRead = _MaxRowsToRead;
            Filter = _Filter;

        }

      
    }
}
